import { Provide } from '@midwayjs/core';
import { Repository } from 'typeorm';
import { Edgroup } from '../../entity/firmware/edgroup.entity';
import { InjectEntityModel } from '@midwayjs/typeorm';

@Provide()
export class EdgroupService {
  @InjectEntityModel(Edgroup)
  edgroupRepo: Repository<Edgroup>;

  // 创建教育集团
  async createEdgroup(name: string, photo: string) {
    const edgroup = new Edgroup();
    edgroup.name = name;
    edgroup.photo = photo;
    edgroup.deleted = false;
    return await this.edgroupRepo.save(edgroup);
  }

  // 获取所有教育集团
  async getAllEdgroups(params) {
    const { name, pageNum, pageSize } = params
    const query = this.edgroupRepo.createQueryBuilder('edgroup')
      .where('edgroup.deleted != :deleted', { deleted: true });
    if (name) {
      query.andWhere('edgroup.name LIKE :name', { name: `%${name}%` });
    }
    if (pageNum) {
      // 添加分页查询
      query.skip((pageNum - 1) * pageSize).take(pageSize);
    }
    // 查询总数 count
    const total = await query.getCount();

    return {
      data: await query.getMany(), // 加载关联的教育集团
      total: total
    }
  }

  // 根据 ID 获取单个教育集团
  async getEdgroupById(id: number) {
    return await this.edgroupRepo.findOneBy({ id });
  }

  // 更新教育集团
  async updateEdgroup(id: number, name?: string, photo?: string) {
    const edgroup = await this.getEdgroupById(id);
    if (!edgroup) return null;

    if (name !== undefined) edgroup.name = name;
    if (photo !== undefined) edgroup.photo = photo;

    return await this.edgroupRepo.save(edgroup);
  }

  // 删除教育集团
  async deleteEdgroup(id: number) {
    const edgroup = await this.getEdgroupById(id)
    edgroup.deleted = true
    await this.edgroupRepo.save(edgroup);
    return await this.edgroupRepo.save(edgroup);
  }
}
